// Construct denormalize GPS data

*houskeeping
clear

local stdvevbeta 0.00659957 //stdevDenmark
local meanbeta 0.9402865858818421 // This is a guess of the mean beta in 2000 - can be matched to mean patience predicted by model but does not imapact results for standard deviation of patience by country - so for all purposes can be set to anything


**********************************************************************************************
**********************************************************************************************
**********************************************************************************************
**********************************************************************************************
**********************************************************************************************
**********************************************************************************************
**********************************************************************************************
**********************************************************************************************


use "$base/InputData/individual_v11.dta", clear

rename isocode countrycode
kountry countrycode, from(iso3c) geo(undet)


sort countrycode

merge countrycode using "$base/InputData/popWDI2000.dta"

drop if missing( sp_pop_totl)

drop if missing(patience)

gen wgt2=wgt*sp_
drop _merge



drop if region==""
sort region


tempfile temp
save `temp'
collapse (mean) regmean=patience [aweight=wgt2], by(region)
sort region
merge region using `temp'
gen normpatience=patience-regmean


qui summarize normpatience [aweight=wgt2]  if GEO=="Northern Europe" | GEO=="Western Europe"


replace normpatience=(normpatience-r(mean))/r(sd)
gen denormpatience=normpatience*`stdvevbeta'+`meanbeta'


keep region countrycode GEO wgt2 denormpatience sp_pop_totl


sort countrycode region



save "$base/Outputs/Data/denormpatience.dta", replace
outsheet region countrycode GEO wgt2 denormpatience using "$base/Outputs/Data/denormpatience.csv", comma replace





capture program drop my_summarize
program define my_summarize
    local statistics skewness kurtosis sd
    summ  denormpatience [aweight=wgt2], detail
 foreach s of local statistics {
        gen `s' = r(`s') in 1
    }
    keep in 1
    keep countrycode `statistics'  sp_pop_totl
    exit
end


runby my_summarize, by(countrycode) verbose


rename sp_pop_totl pop


gsort -sd

outsheet countrycode skewness kurtosis sd pop using "$base/Outputs/Data/sdByCountry.csv", comma replace

clear
